
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>

// Thread function
void* thread_func(void* id)
{
	long tid = 0;
	tid = (long)id;
	printf("Thread #%ld is working!\n", tid);
	pthread_exit(NULL);
}

int main(int argc, char** argv)
{
	const int MAX_THREADS = 5;
	pthread_t threads[MAX_THREADS];	//array for the threads
	pthread_attr_t attr;	
	int result;
   	long i;
   	
   	// Make threads joinable
   	pthread_attr_init(&attr);
   	pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
   	
   	for(i=0; i<MAX_THREADS; i++)
	{
      		printf("In main: creating thread %ld\n", i);
      		result = pthread_create(&threads[i], &attr, thread_func, (void *)i);
      		if (result)
			{
         		printf("ERROR; return code from pthread_create() is %d\n", result);
         		exit(-1);
      		}			
   	}

	// Free attribute and wait for threads to finish
	pthread_attr_destroy(&attr);
	for(i=0; i<MAX_THREADS; i++)
	{
		result = pthread_join(threads[i], NULL);
		if(result)
		{
			printf("Error joining threads, return code: %d\n", result);
			exit(-1);
		}
	}
   	
   	pthread_exit(NULL);
	printf("Exiting...\n");
	return 0;
}

